{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Uncertainty calculation for model: HM2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import the libraries\n",
    "import ee\n",
    "import pandas as pd\n",
    "import os\n",
    "import numpy as np\n",
    "import random\n",
    "from random import sample\n",
    "import itertools \n",
    "import geopandas as gpd\n",
    "from sklearn.metrics import r2_score\n",
    "from termcolor import colored # this is allocate colour and fonts type for the print title and text\n",
    "from IPython.display import display, HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#set the working directory of local drive for Grid search result table loading\n",
    "# os.getcwd()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# initialize the earth engine API\n",
    "ee.Initialize()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1 Load the required composites, images and settings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "#definet the color pallette\n",
    "vibgYOR = ['330044', '220066', '1133cc', '33dd00', 'ffda21', 'ff6622', 'd10000']\n",
    "compositeImage =ee.Image(\"users/leonidmoore/ForestBiomass/20200915_Forest_Biomass_Predictors_Image\")\n",
    "compositeImageNew = ee.Image(\"projects/crowtherlab/Composite/CrowtherLab_Composite_30ArcSec\");\n",
    "unboundedGeo = ee.Geometry.Polygon([-180, 88, 0, 88, 180, 88, 180, -88, 0, -88, -180, -88], None, False)\n",
    "# generete the pixel area map\n",
    "pixelArea = ee.Image.pixelArea().divide(10000) # to ha unit\n",
    "# load the biome layer\n",
    "biomeLayer = compositeImage.select(\"WWF_Biome\")\n",
    "biomeMask = biomeLayer.mask(biomeLayer.neq(98)).mask(biomeLayer.neq(99)).gt(0)\n",
    "# load the mean maps for present and potential\n",
    "# load the carbon concentration map\n",
    "carbonConcentration = ee.Image(\"users/leonidmoore/ForestBiomass/Biome_level_Wood_Carbon_Conentration_Map\")\n",
    "# load the biomass density layers\n",
    "mergedAGB_PresentMean =  ee.Image(\"users/leonidmoore/ForestBiomass/SpawnMap/Spawn_Harmonized_AGB_density_Map_1km\").select('agb').unmask() \n",
    "mergedAGB_PotentialMean = ee.Image(\"users/nordmannmoore/ForestBiomass/RemoteSensingModel/EnsambleMaps/Predicted_HM2_Potential_density_Ensambled_Mean\").unmask()\n",
    "# define the standardized projection\n",
    "stdProj = mergedAGB_PresentMean.projection()\n",
    "# load the two forest cover layer for existing and potential forest\n",
    "presentForestCover = compositeImage.select('PresentTreeCover').unmask()# make sure it's in  0-1 scale\n",
    "potentialForestCover = ee.Image(\"users/leonidmoore/ForestBiomass/Bastin_et_al_2019_Potential_Forest_Cover_Adjusted\").unmask() # make sure it's in  0-1 scale\n",
    "\n",
    "# define the present and potential forest cover masks\n",
    "presentMask = presentForestCover.gt(0)\n",
    "potentialMask = potentialForestCover.gt(0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2 Calculate the present and potential AGB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# check the difference of the two density maps\n",
    "potentialHigher = mergedAGB_PotentialMean.multiply(pixelArea).subtract(mergedAGB_PresentMean.multiply(pixelArea)).gte(0)\n",
    "potentialLower = mergedAGB_PotentialMean.multiply(pixelArea).subtract(mergedAGB_PresentMean.multiply(pixelArea)).lt(0)\n",
    "# replace the lower potential value by present biomass density value\n",
    "potentialAGB_Density = mergedAGB_PresentMean.multiply(potentialLower).add(mergedAGB_PotentialMean.multiply(potentialHigher))\n",
    "presentAGB_Density = mergedAGB_PresentMean\n",
    "# get the abs of present and potential AGB\n",
    "presentAGB_Abs = presentAGB_Density.multiply(pixelArea).multiply(presentMask).divide(1000000000)\n",
    "potentialAGB_Abs = potentialAGB_Density.multiply(pixelArea).multiply(potentialMask).divide(1000000000)\n",
    "\n",
    "# presentAGB_Abs_Sum = presentAGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                  geometry = unboundedGeo,\n",
    "#                                                  crs = 'EPSG:4326',\n",
    "#                                                  crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                  maxPixels = 1e9)\n",
    "# # print the estimation out\n",
    "# print(colored('The present AGB:', 'blue', attrs=['bold']),presentAGB_Abs_Sum.getInfo())\n",
    "# potentialAGB_Abs_Sum = potentialAGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                      geometry = unboundedGeo,\n",
    "#                                                      crs = 'EPSG:4326',\n",
    "#                                                      crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                      maxPixels = 1e9)\n",
    "# # print the estimation out\n",
    "# print(colored('The potential AGB:', 'blue', attrs=['bold']),potentialAGB_Abs_Sum.getInfo())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3 Calculate the Upper and Lower of present and potential AGB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the present prediction lower and upper layer\n",
    "mergedPredictionInterval = ee.Image(\"users/leonidmoore/ForestBiomass/SpawnMap/Spawn_Harmonized_AGB_density_Map_1km\").select('err').unmask()\n",
    "presentAGB_Lower1 = mergedAGB_PresentMean.subtract(mergedPredictionInterval)\n",
    "presentAGB_Lower = presentAGB_Lower1.mask(presentAGB_Lower1.gte(0)).unmask()\n",
    "presentAGB_Upper = mergedAGB_PresentMean.add(mergedPredictionInterval);\n",
    "\n",
    "# get the upper and lower layer\n",
    "mergedAGB_PotentialLower = ee.Image(\"users/nordmannmoore/ForestBiomass/RemoteSensingModel/EnsambleMaps/Predicted_HM2_Potential_density_Ensambled_Percentile\").select(['lower']).unmask() \n",
    "mergedAGB_PotentialUpper = ee.Image(\"users/nordmannmoore/ForestBiomass/RemoteSensingModel/EnsambleMaps/Predicted_HM2_Potential_density_Ensambled_Percentile\").select(['upper']).unmask() \n",
    "\n",
    "mergedAGB_PotentialLower1 = presentAGB_Lower.multiply(potentialLower).add(mergedAGB_PotentialLower.multiply(potentialHigher))\n",
    "mergedAGB_PotentialUpper1 = presentAGB_Upper.multiply(potentialLower).add(mergedAGB_PotentialUpper.multiply(potentialHigher))\n",
    "\n",
    "# define the masks to mask the present and potential lower maps\n",
    "potentialAGB_Lower_Larger = mergedAGB_PotentialLower1.subtract(presentAGB_Lower).gte(0) # potential is larger than present mean\n",
    "potentialAGB_Lower_Smaller = mergedAGB_PotentialLower1.subtract(presentAGB_Lower).lt(0)\n",
    "# define the masks to mask the present and potential upper maps\n",
    "potentialAGB_Upper_Larger = mergedAGB_PotentialUpper1.subtract(presentAGB_Upper).gte(0) # potential is larger than present upper\n",
    "potentialAGB_Upper_Smaller = mergedAGB_PotentialUpper1.subtract(presentAGB_Upper).lt(0)\n",
    "\n",
    "# replace the lower potential value by present biomass density value\n",
    "potentialAGB_AdjLower = mergedAGB_PotentialLower.multiply(potentialAGB_Lower_Larger).add(presentAGB_Lower.multiply(potentialAGB_Lower_Smaller))\n",
    "potentialAGB_AdjUpper = mergedAGB_PotentialUpper.multiply(potentialAGB_Upper_Larger).add(presentAGB_Upper.multiply(potentialAGB_Upper_Smaller))\n",
    "\n",
    "# present lower and higher\n",
    "presentAGB_Lower_Abs = presentAGB_Lower.multiply(pixelArea).multiply(presentMask).divide(1000000000)\n",
    "presentAGB_Upper_Abs = presentAGB_Upper.multiply(pixelArea).multiply(presentMask).divide(1000000000)\n",
    "\n",
    "# abs potential lower and higher\n",
    "potentialAGB_Lower_Abs = potentialAGB_AdjLower.multiply(pixelArea).multiply(potentialMask).divide(1000000000)\n",
    "potentialAGB_Upper_Abs = potentialAGB_AdjUpper.multiply(pixelArea).multiply(potentialMask).divide(1000000000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Calculate the present AGB lower\n",
    "# presentAGB_Lower_Sum = presentAGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                          geometry = unboundedGeo,\n",
    "#                                                          crs = 'EPSG:4326',\n",
    "#                                                          crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                          maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present AGB Lower:', 'blue', attrs=['bold']),presentAGB_Lower_Sum.getInfo())\n",
    "\n",
    "# # Calculate the present AGB upper\n",
    "# presentAGB_Upper_Sum = presentAGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                          geometry = unboundedGeo,\n",
    "#                                                          crs = 'EPSG:4326',\n",
    "#                                                          crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                          maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present AGB Upper:', 'blue', attrs=['bold']),presentAGB_Upper_Sum.getInfo())\n",
    "\n",
    "# potentialAGB_Lower_Sum = potentialAGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                              geometry = unboundedGeo,\n",
    "#                                                              crs = 'EPSG:4326',\n",
    "#                                                              crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                              maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential AGB Lower:', 'blue', attrs=['bold']),potentialAGB_Lower_Sum.getInfo())\n",
    "\n",
    "# potentialAGB_Upper_Sum = potentialAGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                              geometry = unboundedGeo,\n",
    "#                                                              crs = 'EPSG:4326',\n",
    "#                                                              crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                              maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential AGB Upper:', 'blue', attrs=['bold']),potentialAGB_Upper_Sum.getInfo())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4 Calculate the Upper and Lower of present and potential Root and TGB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the root shoot map\n",
    "rootShootRatio = ee.Image(\"users/leonidmoore/ForestBiomass/Root_shoot_ratio_Map\").unmask()\n",
    "rootShootRatioLower = ee.Image(\"users/leonidmoore/ForestBiomass/Root_shoot_ratio_percentile_Map\").select('lower').unmask()\n",
    "rootShootRatioUpper = ee.Image(\"users/leonidmoore/ForestBiomass/Root_shoot_ratio_percentile_Map\").select('upper').unmask()\n",
    "# \n",
    "presentRoot_Lower_Abs = presentAGB_Lower_Abs.multiply(rootShootRatioLower).mask(presentMask)\n",
    "presentRoot_Upper_Abs = presentAGB_Upper_Abs.multiply(rootShootRatioUpper).mask(presentMask)\n",
    "\n",
    "potentialRoot_Lower_Abs = potentialAGB_Lower_Abs.multiply(rootShootRatioLower).mask(potentialMask)\n",
    "potentialRoot_Upper_Abs = potentialAGB_Upper_Abs.multiply(rootShootRatioUpper).mask(potentialMask)\n",
    "\n",
    "presentRoot_Abs = presentAGB_Abs.multiply(rootShootRatio).mask(presentMask)\n",
    "potentialRoot_Abs = potentialAGB_Abs.multiply(rootShootRatio).mask(potentialMask)\n",
    "\n",
    "presentTGB_Abs = presentAGB_Abs.multiply(rootShootRatio).add(presentAGB_Abs)#.multiply(presentMask)\n",
    "potentialTGB_Abs = potentialAGB_Abs.multiply(rootShootRatio).add(potentialAGB_Abs)#.multiply(potentialMask)\n",
    "\n",
    "presentTGB  = presentAGB_Density.multiply(rootShootRatio.add(1))\n",
    "# density \n",
    "presentRoot = presentAGB_Density.multiply(rootShootRatio)\n",
    "presentRoot_Lower = presentAGB_Lower.multiply(rootShootRatioLower)\n",
    "presentRoot_Upper = presentAGB_Upper.multiply(rootShootRatioLower)\n",
    "\n",
    "potentialRoot_Lower = potentialAGB_AdjLower.multiply(rootShootRatioLower)\n",
    "potentialRoot_Upper = potentialAGB_AdjUpper.multiply(rootShootRatioLower)\n",
    "\n",
    "presentTGB_Lower = presentAGB_Lower.multiply(rootShootRatioLower).add(presentAGB_Lower)\n",
    "presentTGB_Upper = presentAGB_Upper.multiply(rootShootRatioLower).add(presentAGB_Upper)\n",
    "\n",
    "potentialTGB_Lower = potentialAGB_AdjLower.multiply(rootShootRatioLower).add(potentialAGB_AdjLower)\n",
    "potentialTGB_Upper = potentialAGB_AdjUpper.multiply(rootShootRatioLower).add(potentialAGB_AdjUpper)\n",
    "\n",
    "# presentTGB_Abs_Sum = presentTGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                  geometry = unboundedGeo,\n",
    "#                                                  crs = 'EPSG:4326',\n",
    "#                                                  crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                  maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present TGB:', 'blue', attrs=['bold']),presentTGB_Abs_Sum.getInfo())\n",
    "\n",
    "# potentialTGB_Abs_Sum = potentialTGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                      geometry = unboundedGeo,\n",
    "#                                                      crs = 'EPSG:4326',\n",
    "#                                                      crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                      maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential TGB:', 'blue', attrs=['bold']),potentialTGB_Abs_Sum.getInfo())\n",
    "\n",
    "# presentRoot_Abs_Sum = presentRoot_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                    geometry = unboundedGeo,\n",
    "#                                                    crs = 'EPSG:4326',\n",
    "#                                                    crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                    maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Roots:', 'blue', attrs=['bold']),presentRoot_Abs_Sum.getInfo())\n",
    "\n",
    "# potentialRoot_Abs_Sum = potentialRoot_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Roots:', 'blue', attrs=['bold']),potentialRoot_Abs_Sum.getInfo())\n",
    "\n",
    "# presentRoot_Lower_Sum = presentRoot_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Roots Lower:', 'blue', attrs=['bold']),presentRoot_Lower_Sum.getInfo())\n",
    "\n",
    "# presentRoot_Upper_Sum = presentRoot_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Roots Upper:', 'blue', attrs=['bold']),presentRoot_Upper_Sum.getInfo())\n",
    "\n",
    "# potentialRoot_Lower_Sum = potentialRoot_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Roots Lower:', 'blue', attrs=['bold']),potentialRoot_Lower_Sum.getInfo())\n",
    "# potentialRoot_Upper_Sum = potentialRoot_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Roots Upper:', 'blue', attrs=['bold']),potentialRoot_Upper_Sum.getInfo())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "presentTGB_Lower_Abs = presentAGB_Lower_Abs.multiply(rootShootRatioLower.add(1))\n",
    "presentTGB_Upper_Abs = presentAGB_Upper_Abs.multiply(rootShootRatioUpper.add(1))\n",
    "\n",
    "potentialTGB_Lower_Abs = potentialAGB_Lower_Abs.multiply(rootShootRatioLower.add(1))\n",
    "potentialTGB_Upper_Abs = potentialAGB_Upper_Abs.multiply(rootShootRatioUpper.add(1))\n",
    "\n",
    "# presentTGB_Lower_Sum = presentTGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present TGB Lower:', 'blue', attrs=['bold']),presentTGB_Lower_Sum.getInfo())\n",
    "\n",
    "# presentTGB_Upper_Sum = presentTGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present TGB Upper:', 'blue', attrs=['bold']),presentTGB_Upper_Sum.getInfo())\n",
    "\n",
    "# potentialTGB_Lower_Sum = potentialTGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential TGB Lower:', 'blue', attrs=['bold']),potentialTGB_Lower_Sum.getInfo())\n",
    "# potentialTGB_Upper_Sum = potentialTGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential TGB Upper:', 'blue', attrs=['bold']),potentialTGB_Upper_Sum.getInfo())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5 Calculate the Upper and Lower of present and potential Root and PGB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the dead wood and litter layer\n",
    "deadWoodLitterRatio = ee.Image(\"users/leonidmoore/ForestBiomass/DeadWoodLitter/DeadWood_Litter_Ratio_Map\").unmask()\n",
    "deadWoodLitterRatioLower = ee.Image(\"users/leonidmoore/ForestBiomass/DeadWoodLitter/DeadWood_Litter_Ratio_Lower_Map\").unmask()\n",
    "deadWoodLitterRatioUpper = ee.Image(\"users/leonidmoore/ForestBiomass/DeadWoodLitter/DeadWood_Litter_Ratio_Upper_Map\").unmask()\n",
    "\n",
    "# calculate the present and potential PGB\n",
    "presentPGB_Abs = presentTGB_Abs.multiply(deadWoodLitterRatio)\n",
    "potentialPGB_Abs = potentialTGB_Abs.multiply(deadWoodLitterRatio)\n",
    "\n",
    "# calculate the present and potential dead wood and litter\n",
    "presentLitter_Abs = presentTGB_Abs.multiply(deadWoodLitterRatio.subtract(1))\n",
    "potentialLitter_Abs = potentialTGB_Abs.multiply(deadWoodLitterRatio.subtract(1))\n",
    "\n",
    "# calculate the present Dead wood and litter\n",
    "presentLitter_Lower_Abs = presentTGB_Lower_Abs.multiply(deadWoodLitterRatioLower.subtract(1))\n",
    "presentLitter_Upper_Abs = presentTGB_Upper_Abs.multiply(deadWoodLitterRatioUpper.subtract(1))\n",
    "# calculate the potential dead wood and litter\n",
    "potentialLitter_Lower_Abs = potentialTGB_Lower_Abs.multiply(deadWoodLitterRatioLower.subtract(1))\n",
    "potentialLitter_Upper_Abs = potentialTGB_Upper_Abs.multiply(deadWoodLitterRatioUpper.subtract(1))\n",
    "# get the densities\n",
    "presentPGB_Lower = presentTGB_Lower.multiply(deadWoodLitterRatioLower)\n",
    "presentPGB_Upper = presentTGB_Upper.multiply(deadWoodLitterRatioUpper)\n",
    "\n",
    "potentialPGB_Lower = potentialTGB_Lower.multiply(deadWoodLitterRatioLower)\n",
    "potentialPGB_Lower = potentialTGB_Lower.multiply(deadWoodLitterRatioUpper)\n",
    "\n",
    "presentLitter_Lower = presentTGB_Lower.multiply(deadWoodLitterRatioLower.subtract(1))\n",
    "presentLitter_Upper = presentTGB_Upper.multiply(deadWoodLitterRatioUpper.subtract(1))\n",
    "\n",
    "potentialLitter_Lower = potentialTGB_Lower.multiply(deadWoodLitterRatioLower.subtract(1))\n",
    "potentialLitter_Lower = potentialTGB_Lower.multiply(deadWoodLitterRatioUpper.subtract(1))\n",
    "\n",
    "# presentPGB_Abs_Sum = presentPGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present PGB:', 'blue', attrs=['bold']),presentPGB_Abs_Sum.getInfo())\n",
    "\n",
    "# potentialPGB_Abs_Sum = potentialPGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential PGB:', 'blue', attrs=['bold']),potentialPGB_Abs_Sum.getInfo())\n",
    "\n",
    "# presentLitter_Abs_Sum = presentLitter_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Dead wood and litter:', 'blue', attrs=['bold']),presentLitter_Abs_Sum.getInfo())\n",
    "\n",
    "# potentialLitter_Abs_Sum = potentialLitter_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Dead wood and litter:', 'blue', attrs=['bold']),potentialLitter_Abs_Sum.getInfo())\n",
    "\n",
    "# presentLitter_Lower_Sum = presentLitter_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Dead wood and litter Lower:', 'blue', attrs=['bold']),presentLitter_Lower_Sum.getInfo())\n",
    "\n",
    "# presentLitter_Upper_Sum = presentLitter_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Dead wood and litter Upper:', 'blue', attrs=['bold']),presentLitter_Upper_Sum.getInfo())\n",
    "\n",
    "# potentialLitter_Lower_Sum = potentialLitter_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Dead wood and litter Lower:', 'blue', attrs=['bold']),potentialLitter_Lower_Sum.getInfo())\n",
    "\n",
    "# potentialLitter_Upper_Sum = potentialLitter_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Dead wood and litter Upper:', 'blue', attrs=['bold']),potentialLitter_Upper_Sum.getInfo())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "# calculate the present PGB Lower and Upper\n",
    "presentPGB_Lower_Abs = presentTGB_Lower_Abs.multiply(deadWoodLitterRatioLower)\n",
    "presentPGB_Upper_Abs = presentTGB_Upper_Abs.multiply(deadWoodLitterRatioUpper)\n",
    "# calculate the potential PGB Lower and Upper\n",
    "potentialPGB_Lower_Abs = potentialTGB_Lower_Abs.multiply(deadWoodLitterRatioLower)\n",
    "potentialPGB_Upper_Abs = potentialTGB_Upper_Abs.multiply(deadWoodLitterRatioUpper)\n",
    "\n",
    "presentPGB_D = presentAGB_Density.multiply(rootShootRatio.add(1)).multiply(deadWoodLitterRatio)\n",
    "potentialPGB_D = potentialAGB_Density.multiply(rootShootRatio.add(1)).multiply(deadWoodLitterRatio)\n",
    "\n",
    "# presentPGB_Lower_Sum = presentPGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present PGB Lower:', 'blue', attrs=['bold']),presentPGB_Lower_Sum.getInfo())\n",
    "\n",
    "# presentPGB_Upper_Sum = presentPGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present PGB Upper:', 'blue', attrs=['bold']),presentPGB_Upper_Sum.getInfo())\n",
    "\n",
    "# potentialPGB_Lower_Sum = potentialPGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential PGB Lower:', 'blue', attrs=['bold']),potentialPGB_Lower_Sum.getInfo())\n",
    "\n",
    "# potentialPGB_Upper_Sum = potentialPGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential PGB Upper:', 'blue', attrs=['bold']),potentialPGB_Upper_Sum.getInfo())\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6 Export the upper and lower images to Assets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the carbon density layers\n",
    "SandermannCarbonDiff = ee.Image(\"users/leonidmoore/ForestBiomass/SoilOrganicCarbonModel/SOCS_0_200cm_Diff_1km_Present_subtract_NoLU\").unmask()\n",
    "SandermannCarbonPresent = ee.Image(\"users/leonidmoore/ForestBiomass/SoilOrganicCarbonModel/SOCS_0_200cm_1km_Present\").unmask()\n",
    "\n",
    "# mask the diffrence layer\n",
    "SandermannCarbonLoss = SandermannCarbonDiff.multiply(SandermannCarbonDiff.gt(0))\n",
    "\n",
    "# load the present and potential forest cover\n",
    "presentForestCover = compositeImage.select('PresentTreeCover').unmask() # uniform with potential in the  0-1 scale\n",
    "potentialCoverAdjusted = ee.Image(\"users/leonidmoore/ForestBiomass/Bastin_et_al_2019_Potential_Forest_Cover_Adjusted\").unmask().rename('PotentialForestCover')\n",
    "# define the present and potential forest cover masks\n",
    "presentMask = presentForestCover.gt(0)\n",
    "potentialMask = potentialCoverAdjusted.gte(0.1)\n",
    "\n",
    "# calculate the sum of the potential in soil with the consideration of forest cover\n",
    "SandermannCarbonStockLoss = SandermannCarbonLoss.multiply(pixelArea).divide(1000000000).mask(biomeMask).mask(potentialMask).multiply(potentialCoverAdjusted)\n",
    "\n",
    "# add the soil into the PGB as the total potential\n",
    "potentialTotal_Abs = potentialPGB_Abs.add(SandermannCarbonStockLoss)\n",
    "# compose those bands into an image\n",
    "lowerUpperImage = presentAGB_Lower_Abs.rename('preAGB_Lower').addBands(presentAGB_Upper_Abs.rename('preAGB_Upper')).addBands(potentialAGB_Lower_Abs.rename('potAGB_Lower')).addBands(potentialAGB_Upper_Abs.rename('potAGB_Upper')).addBands(presentRoot_Lower_Abs.rename('preRoot_Lower')).addBands(presentRoot_Upper_Abs.rename('preRoot_Upper')).addBands(potentialRoot_Lower_Abs.rename('potRoot_Lower')).addBands(potentialRoot_Upper_Abs.rename('potRoot_Upper')).addBands(presentLitter_Lower_Abs.rename('preLitter_Lower')).addBands(presentLitter_Upper_Abs.rename('preLitter_Upper')).addBands(potentialLitter_Lower_Abs.rename('potLitter_Lower')).addBands(potentialLitter_Upper_Abs.rename('potLitter_Upper')).addBands(potentialTotal_Abs.rename('PotentialTotal'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'state': 'READY',\n",
       " 'description': 'HM2_Upper_Lower_Uncertainty_maps_Export',\n",
       " 'creation_timestamp_ms': 1690806660439,\n",
       " 'update_timestamp_ms': 1690806660439,\n",
       " 'start_timestamp_ms': 0,\n",
       " 'task_type': 'EXPORT_IMAGE',\n",
       " 'id': '5BJOQ7FEHCB3NDH37FPSAMAK',\n",
       " 'name': 'projects/earthengine-legacy/operations/5BJOQ7FEHCB3NDH37FPSAMAK'}"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "exportUpperLower = ee.batch.Export.image.toAsset(image = lowerUpperImage,\n",
    "                                               description = 'HM2_Upper_Lower_Uncertainty_maps_Export',\n",
    "                                               assetId = 'users/leonidmoore/ForestBiomass/UncertaintyFigure/HM2_Lower_Upper_Map',\n",
    "                                               region = unboundedGeo,\n",
    "                                               crs = 'EPSG:4326',\n",
    "                                               crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                               maxPixels = 1e13)\n",
    "# start the export task\n",
    "exportUpperLower.start()\n",
    "# show the task status\n",
    "exportUpperLower.status()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6 Calculate the Abs for different parts at biome level"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[34mThe biomass partition results in biome: \n",
      "\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>PresentAGB</th>\n",
       "      <th>PotentialAGB</th>\n",
       "      <th>PresentRoot</th>\n",
       "      <th>PotentialRoot</th>\n",
       "      <th>PresentTGB</th>\n",
       "      <th>PotentialTGB</th>\n",
       "      <th>PresentLitter</th>\n",
       "      <th>PotentialLitter</th>\n",
       "      <th>PresentPGB</th>\n",
       "      <th>PotentialPGB</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>136.1</td>\n",
       "      <td>179.4</td>\n",
       "      <td>36.7</td>\n",
       "      <td>47.4</td>\n",
       "      <td>172.8</td>\n",
       "      <td>226.8</td>\n",
       "      <td>38.0</td>\n",
       "      <td>49.9</td>\n",
       "      <td>210.8</td>\n",
       "      <td>276.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>5.2</td>\n",
       "      <td>13.1</td>\n",
       "      <td>1.4</td>\n",
       "      <td>3.4</td>\n",
       "      <td>6.5</td>\n",
       "      <td>16.5</td>\n",
       "      <td>1.4</td>\n",
       "      <td>3.6</td>\n",
       "      <td>8.0</td>\n",
       "      <td>20.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1.7</td>\n",
       "      <td>3.8</td>\n",
       "      <td>0.4</td>\n",
       "      <td>1.0</td>\n",
       "      <td>2.2</td>\n",
       "      <td>4.8</td>\n",
       "      <td>0.5</td>\n",
       "      <td>1.0</td>\n",
       "      <td>2.7</td>\n",
       "      <td>5.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>34.6</td>\n",
       "      <td>59.8</td>\n",
       "      <td>8.9</td>\n",
       "      <td>15.2</td>\n",
       "      <td>43.5</td>\n",
       "      <td>75.0</td>\n",
       "      <td>14.3</td>\n",
       "      <td>24.7</td>\n",
       "      <td>57.8</td>\n",
       "      <td>99.7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>16.4</td>\n",
       "      <td>22.2</td>\n",
       "      <td>4.4</td>\n",
       "      <td>5.9</td>\n",
       "      <td>20.7</td>\n",
       "      <td>28.2</td>\n",
       "      <td>6.8</td>\n",
       "      <td>9.3</td>\n",
       "      <td>27.5</td>\n",
       "      <td>37.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>36.4</td>\n",
       "      <td>49.3</td>\n",
       "      <td>9.7</td>\n",
       "      <td>13.3</td>\n",
       "      <td>46.1</td>\n",
       "      <td>62.6</td>\n",
       "      <td>36.8</td>\n",
       "      <td>50.0</td>\n",
       "      <td>82.9</td>\n",
       "      <td>112.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>31.5</td>\n",
       "      <td>71.8</td>\n",
       "      <td>9.6</td>\n",
       "      <td>21.8</td>\n",
       "      <td>41.1</td>\n",
       "      <td>93.6</td>\n",
       "      <td>9.0</td>\n",
       "      <td>20.6</td>\n",
       "      <td>50.2</td>\n",
       "      <td>114.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>3.8</td>\n",
       "      <td>18.9</td>\n",
       "      <td>1.1</td>\n",
       "      <td>5.5</td>\n",
       "      <td>4.9</td>\n",
       "      <td>24.4</td>\n",
       "      <td>1.6</td>\n",
       "      <td>8.1</td>\n",
       "      <td>6.5</td>\n",
       "      <td>32.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>1.2</td>\n",
       "      <td>2.7</td>\n",
       "      <td>0.4</td>\n",
       "      <td>0.8</td>\n",
       "      <td>1.6</td>\n",
       "      <td>3.5</td>\n",
       "      <td>0.3</td>\n",
       "      <td>0.8</td>\n",
       "      <td>1.9</td>\n",
       "      <td>4.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>2.7</td>\n",
       "      <td>7.7</td>\n",
       "      <td>0.8</td>\n",
       "      <td>2.0</td>\n",
       "      <td>3.4</td>\n",
       "      <td>9.7</td>\n",
       "      <td>1.1</td>\n",
       "      <td>3.2</td>\n",
       "      <td>4.5</td>\n",
       "      <td>12.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>3.1</td>\n",
       "      <td>7.7</td>\n",
       "      <td>0.9</td>\n",
       "      <td>2.3</td>\n",
       "      <td>4.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>3.2</td>\n",
       "      <td>8.0</td>\n",
       "      <td>7.3</td>\n",
       "      <td>17.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>3.0</td>\n",
       "      <td>8.6</td>\n",
       "      <td>0.9</td>\n",
       "      <td>2.7</td>\n",
       "      <td>3.9</td>\n",
       "      <td>11.3</td>\n",
       "      <td>0.8</td>\n",
       "      <td>2.4</td>\n",
       "      <td>4.7</td>\n",
       "      <td>13.7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>2.0</td>\n",
       "      <td>21.8</td>\n",
       "      <td>0.6</td>\n",
       "      <td>5.7</td>\n",
       "      <td>2.6</td>\n",
       "      <td>27.5</td>\n",
       "      <td>0.5</td>\n",
       "      <td>5.8</td>\n",
       "      <td>3.1</td>\n",
       "      <td>33.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>1.1</td>\n",
       "      <td>2.1</td>\n",
       "      <td>0.2</td>\n",
       "      <td>0.4</td>\n",
       "      <td>1.3</td>\n",
       "      <td>2.5</td>\n",
       "      <td>0.3</td>\n",
       "      <td>0.6</td>\n",
       "      <td>1.6</td>\n",
       "      <td>3.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>sum</th>\n",
       "      <td>278.8</td>\n",
       "      <td>468.9</td>\n",
       "      <td>76.0</td>\n",
       "      <td>127.4</td>\n",
       "      <td>354.6</td>\n",
       "      <td>596.4</td>\n",
       "      <td>114.6</td>\n",
       "      <td>188.0</td>\n",
       "      <td>469.5</td>\n",
       "      <td>784.3</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     PresentAGB  PotentialAGB  PresentRoot  PotentialRoot  PresentTGB  \\\n",
       "0         136.1         179.4         36.7           47.4       172.8   \n",
       "1           5.2          13.1          1.4            3.4         6.5   \n",
       "2           1.7           3.8          0.4            1.0         2.2   \n",
       "3          34.6          59.8          8.9           15.2        43.5   \n",
       "4          16.4          22.2          4.4            5.9        20.7   \n",
       "5          36.4          49.3          9.7           13.3        46.1   \n",
       "6          31.5          71.8          9.6           21.8        41.1   \n",
       "7           3.8          18.9          1.1            5.5         4.9   \n",
       "8           1.2           2.7          0.4            0.8         1.6   \n",
       "9           2.7           7.7          0.8            2.0         3.4   \n",
       "10          3.1           7.7          0.9            2.3         4.0   \n",
       "11          3.0           8.6          0.9            2.7         3.9   \n",
       "12          2.0          21.8          0.6            5.7         2.6   \n",
       "13          1.1           2.1          0.2            0.4         1.3   \n",
       "sum       278.8         468.9         76.0          127.4       354.6   \n",
       "\n",
       "     PotentialTGB  PresentLitter  PotentialLitter  PresentPGB  PotentialPGB  \n",
       "0           226.8           38.0             49.9       210.8         276.8  \n",
       "1            16.5            1.4              3.6         8.0          20.1  \n",
       "2             4.8            0.5              1.0         2.7           5.8  \n",
       "3            75.0           14.3             24.7        57.8          99.7  \n",
       "4            28.2            6.8              9.3        27.5          37.5  \n",
       "5            62.6           36.8             50.0        82.9         112.6  \n",
       "6            93.6            9.0             20.6        50.2         114.1  \n",
       "7            24.4            1.6              8.1         6.5          32.5  \n",
       "8             3.5            0.3              0.8         1.9           4.3  \n",
       "9             9.7            1.1              3.2         4.5          12.9  \n",
       "10           10.0            3.2              8.0         7.3          17.9  \n",
       "11           11.3            0.8              2.4         4.7          13.7  \n",
       "12           27.5            0.5              5.8         3.1          33.3  \n",
       "13            2.5            0.3              0.6         1.6           3.1  \n",
       "sum         596.4          114.6            188.0       469.5         784.3  "
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Stack the absolute biomass layers into an Image.\n",
    "absImage = presentAGB_Abs.rename('PresentAGB').addBands(potentialAGB_Abs.rename('PotentialAGB')).addBands(presentRoot_Abs.rename('PresentRoot')).addBands(potentialRoot_Abs.rename('PotentialRoot')).addBands(presentTGB_Abs.rename('PresentTGB')).addBands(potentialTGB_Abs.rename('PotentialTGB')).addBands(presentLitter_Abs.rename('PresentLitter')).addBands(potentialLitter_Abs.rename('PotentialLitter')).addBands(presentPGB_Abs.rename('PresentPGB')).addBands(potentialPGB_Abs.rename('PotentialPGB'))\n",
    "\n",
    "# define the function to do the biome level statistics which could be applied by map      \n",
    "def biomeLevelStat(biome):\n",
    "    perBiomeMask = biomeLayer.eq(ee.Number(biome))\n",
    "    masked_img = absImage.mask(perBiomeMask)\n",
    "    output = masked_img.reduceRegion(reducer= ee.Reducer.sum(),\n",
    "                                     geometry= unboundedGeo,\n",
    "                                     crs='EPSG:4326',\n",
    "                                     crsTransform=[0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                     maxPixels= 1e13)\n",
    "    return output#.getInfo().get('Present')\n",
    "\n",
    "\n",
    "biomeList = ee.List([1,2,3,4,5,6,7,8,9,10,11,12,13,14])\n",
    "statisticTable = biomeList.map(biomeLevelStat).getInfo()\n",
    "# transform into data frame\n",
    "outputTable = pd.DataFrame(statisticTable,columns =['PresentAGB','PotentialAGB','PresentRoot','PotentialRoot','PresentTGB','PotentialTGB','PresentLitter','PotentialLitter','PresentPGB','PotentialPGB']).round(1)\n",
    "outputTable.loc['sum'] = outputTable.sum() \n",
    "outputTable.to_csv('Data/BiomeLevelStatistics/StatisticsForModels/HM2_Abs_for_diff_parts_at_Biome_Level.csv',header=True,mode='w+')\n",
    "print(colored('The biomass partition results in biome: \\n', 'blue', attrs=['bold']))\n",
    "outputTable.head(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If you got the error 'EEException: Too many concurrent aggregations.', please re-run this chunck of code again."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7 Calculate the Abs for different parts at biome level"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[34mThe biomass partition results in biome: \n",
      "\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>preAGB_Lower</th>\n",
       "      <th>preAGB_Upper</th>\n",
       "      <th>potAGB_Lower</th>\n",
       "      <th>potAGB_Upper</th>\n",
       "      <th>preRoot_Lower</th>\n",
       "      <th>preRoot_Upper</th>\n",
       "      <th>potRoot_Lower</th>\n",
       "      <th>potRoot_Upper</th>\n",
       "      <th>preLitter_Lower</th>\n",
       "      <th>preLitter_Upper</th>\n",
       "      <th>potLitter_Lower</th>\n",
       "      <th>potLitter_Upper</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>61.4</td>\n",
       "      <td>211.0</td>\n",
       "      <td>161.0</td>\n",
       "      <td>205.2</td>\n",
       "      <td>12.9</td>\n",
       "      <td>70.1</td>\n",
       "      <td>33.7</td>\n",
       "      <td>66.3</td>\n",
       "      <td>11.2</td>\n",
       "      <td>84.3</td>\n",
       "      <td>29.2</td>\n",
       "      <td>81.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2.2</td>\n",
       "      <td>8.2</td>\n",
       "      <td>11.4</td>\n",
       "      <td>14.9</td>\n",
       "      <td>0.5</td>\n",
       "      <td>2.6</td>\n",
       "      <td>2.4</td>\n",
       "      <td>4.5</td>\n",
       "      <td>0.4</td>\n",
       "      <td>3.2</td>\n",
       "      <td>2.1</td>\n",
       "      <td>5.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.8</td>\n",
       "      <td>2.7</td>\n",
       "      <td>3.3</td>\n",
       "      <td>4.2</td>\n",
       "      <td>0.2</td>\n",
       "      <td>0.8</td>\n",
       "      <td>0.7</td>\n",
       "      <td>1.3</td>\n",
       "      <td>0.1</td>\n",
       "      <td>1.1</td>\n",
       "      <td>0.6</td>\n",
       "      <td>1.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>14.8</td>\n",
       "      <td>54.9</td>\n",
       "      <td>51.7</td>\n",
       "      <td>67.4</td>\n",
       "      <td>3.4</td>\n",
       "      <td>16.0</td>\n",
       "      <td>11.7</td>\n",
       "      <td>19.5</td>\n",
       "      <td>5.5</td>\n",
       "      <td>26.2</td>\n",
       "      <td>19.0</td>\n",
       "      <td>32.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>7.8</td>\n",
       "      <td>25.0</td>\n",
       "      <td>18.7</td>\n",
       "      <td>24.5</td>\n",
       "      <td>1.8</td>\n",
       "      <td>7.6</td>\n",
       "      <td>4.4</td>\n",
       "      <td>7.5</td>\n",
       "      <td>2.9</td>\n",
       "      <td>12.1</td>\n",
       "      <td>6.9</td>\n",
       "      <td>11.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>16.7</td>\n",
       "      <td>56.4</td>\n",
       "      <td>42.0</td>\n",
       "      <td>54.2</td>\n",
       "      <td>4.1</td>\n",
       "      <td>16.7</td>\n",
       "      <td>10.3</td>\n",
       "      <td>16.2</td>\n",
       "      <td>14.1</td>\n",
       "      <td>68.6</td>\n",
       "      <td>35.5</td>\n",
       "      <td>66.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>12.9</td>\n",
       "      <td>51.1</td>\n",
       "      <td>60.5</td>\n",
       "      <td>83.5</td>\n",
       "      <td>3.3</td>\n",
       "      <td>18.0</td>\n",
       "      <td>15.6</td>\n",
       "      <td>29.4</td>\n",
       "      <td>2.4</td>\n",
       "      <td>20.7</td>\n",
       "      <td>11.4</td>\n",
       "      <td>33.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>1.5</td>\n",
       "      <td>6.7</td>\n",
       "      <td>15.3</td>\n",
       "      <td>22.6</td>\n",
       "      <td>0.4</td>\n",
       "      <td>2.2</td>\n",
       "      <td>3.9</td>\n",
       "      <td>7.7</td>\n",
       "      <td>0.6</td>\n",
       "      <td>3.3</td>\n",
       "      <td>5.7</td>\n",
       "      <td>11.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>0.5</td>\n",
       "      <td>2.0</td>\n",
       "      <td>2.3</td>\n",
       "      <td>3.2</td>\n",
       "      <td>0.1</td>\n",
       "      <td>0.7</td>\n",
       "      <td>0.6</td>\n",
       "      <td>1.1</td>\n",
       "      <td>0.1</td>\n",
       "      <td>0.8</td>\n",
       "      <td>0.4</td>\n",
       "      <td>1.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>1.1</td>\n",
       "      <td>4.4</td>\n",
       "      <td>6.1</td>\n",
       "      <td>9.2</td>\n",
       "      <td>0.3</td>\n",
       "      <td>1.4</td>\n",
       "      <td>1.4</td>\n",
       "      <td>2.8</td>\n",
       "      <td>0.4</td>\n",
       "      <td>2.1</td>\n",
       "      <td>2.2</td>\n",
       "      <td>4.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>1.3</td>\n",
       "      <td>5.6</td>\n",
       "      <td>5.6</td>\n",
       "      <td>9.3</td>\n",
       "      <td>0.3</td>\n",
       "      <td>2.0</td>\n",
       "      <td>1.5</td>\n",
       "      <td>3.4</td>\n",
       "      <td>1.1</td>\n",
       "      <td>7.1</td>\n",
       "      <td>4.8</td>\n",
       "      <td>11.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>1.3</td>\n",
       "      <td>4.8</td>\n",
       "      <td>7.0</td>\n",
       "      <td>10.2</td>\n",
       "      <td>0.3</td>\n",
       "      <td>2.0</td>\n",
       "      <td>1.9</td>\n",
       "      <td>4.2</td>\n",
       "      <td>0.0</td>\n",
       "      <td>2.7</td>\n",
       "      <td>0.2</td>\n",
       "      <td>5.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>0.8</td>\n",
       "      <td>3.4</td>\n",
       "      <td>16.1</td>\n",
       "      <td>27.8</td>\n",
       "      <td>0.2</td>\n",
       "      <td>1.3</td>\n",
       "      <td>3.8</td>\n",
       "      <td>8.9</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.9</td>\n",
       "      <td>0.4</td>\n",
       "      <td>14.7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>0.5</td>\n",
       "      <td>1.7</td>\n",
       "      <td>1.8</td>\n",
       "      <td>2.3</td>\n",
       "      <td>0.1</td>\n",
       "      <td>0.5</td>\n",
       "      <td>0.4</td>\n",
       "      <td>0.7</td>\n",
       "      <td>0.1</td>\n",
       "      <td>0.6</td>\n",
       "      <td>0.3</td>\n",
       "      <td>0.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>sum</th>\n",
       "      <td>123.6</td>\n",
       "      <td>437.9</td>\n",
       "      <td>402.8</td>\n",
       "      <td>538.5</td>\n",
       "      <td>27.9</td>\n",
       "      <td>141.9</td>\n",
       "      <td>92.3</td>\n",
       "      <td>173.5</td>\n",
       "      <td>38.9</td>\n",
       "      <td>234.7</td>\n",
       "      <td>118.7</td>\n",
       "      <td>283.2</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     preAGB_Lower  preAGB_Upper  potAGB_Lower  potAGB_Upper  preRoot_Lower  \\\n",
       "0            61.4         211.0         161.0         205.2           12.9   \n",
       "1             2.2           8.2          11.4          14.9            0.5   \n",
       "2             0.8           2.7           3.3           4.2            0.2   \n",
       "3            14.8          54.9          51.7          67.4            3.4   \n",
       "4             7.8          25.0          18.7          24.5            1.8   \n",
       "5            16.7          56.4          42.0          54.2            4.1   \n",
       "6            12.9          51.1          60.5          83.5            3.3   \n",
       "7             1.5           6.7          15.3          22.6            0.4   \n",
       "8             0.5           2.0           2.3           3.2            0.1   \n",
       "9             1.1           4.4           6.1           9.2            0.3   \n",
       "10            1.3           5.6           5.6           9.3            0.3   \n",
       "11            1.3           4.8           7.0          10.2            0.3   \n",
       "12            0.8           3.4          16.1          27.8            0.2   \n",
       "13            0.5           1.7           1.8           2.3            0.1   \n",
       "sum         123.6         437.9         402.8         538.5           27.9   \n",
       "\n",
       "     preRoot_Upper  potRoot_Lower  potRoot_Upper  preLitter_Lower  \\\n",
       "0             70.1           33.7           66.3             11.2   \n",
       "1              2.6            2.4            4.5              0.4   \n",
       "2              0.8            0.7            1.3              0.1   \n",
       "3             16.0           11.7           19.5              5.5   \n",
       "4              7.6            4.4            7.5              2.9   \n",
       "5             16.7           10.3           16.2             14.1   \n",
       "6             18.0           15.6           29.4              2.4   \n",
       "7              2.2            3.9            7.7              0.6   \n",
       "8              0.7            0.6            1.1              0.1   \n",
       "9              1.4            1.4            2.8              0.4   \n",
       "10             2.0            1.5            3.4              1.1   \n",
       "11             2.0            1.9            4.2              0.0   \n",
       "12             1.3            3.8            8.9              0.0   \n",
       "13             0.5            0.4            0.7              0.1   \n",
       "sum          141.9           92.3          173.5             38.9   \n",
       "\n",
       "     preLitter_Upper  potLitter_Lower  potLitter_Upper  \n",
       "0               84.3             29.2             81.5  \n",
       "1                3.2              2.1              5.8  \n",
       "2                1.1              0.6              1.6  \n",
       "3               26.2             19.0             32.1  \n",
       "4               12.1              6.9             11.9  \n",
       "5               68.6             35.5             66.2  \n",
       "6               20.7             11.4             33.9  \n",
       "7                3.3              5.7             11.2  \n",
       "8                0.8              0.4              1.3  \n",
       "9                2.1              2.2              4.4  \n",
       "10               7.1              4.8             11.9  \n",
       "11               2.7              0.2              5.8  \n",
       "12               1.9              0.4             14.7  \n",
       "13               0.6              0.3              0.9  \n",
       "sum            234.7            118.7            283.2  "
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Stack the absolute biomass layers into an Image.\n",
    "absPotentialImage = presentAGB_Lower_Abs.rename('preAGB_Lower').addBands(presentAGB_Upper_Abs.rename('preAGB_Upper')).addBands(potentialAGB_Lower_Abs.rename('potAGB_Lower')).addBands(potentialAGB_Upper_Abs.rename('potAGB_Upper')).addBands(presentRoot_Lower_Abs.rename('preRoot_Lower')).addBands(presentRoot_Upper_Abs.rename('preRoot_Upper')).addBands(potentialRoot_Lower_Abs.rename('potRoot_Lower')).addBands(potentialRoot_Upper_Abs.rename('potRoot_Upper')).addBands(presentLitter_Lower_Abs.rename('preLitter_Lower')).addBands(presentLitter_Upper_Abs.rename('preLitter_Upper')).addBands(potentialLitter_Lower_Abs.rename('potLitter_Lower')).addBands(potentialLitter_Upper_Abs.rename('potLitter_Upper'))\n",
    "# define the function to do the biome level statistics which could be applied by map      \n",
    "def biomeLevelStat(biome):\n",
    "    perBiomeMask = biomeLayer.eq(ee.Number(biome))\n",
    "    masked_img = absPotentialImage.mask(perBiomeMask)\n",
    "    output = masked_img.reduceRegion(reducer= ee.Reducer.sum(),\n",
    "                                     geometry= unboundedGeo,\n",
    "                                     crs='EPSG:4326',\n",
    "                                     crsTransform=[0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                     maxPixels= 1e13)\n",
    "    return output#.getInfo().get('Present')\n",
    "\n",
    "\n",
    "biomeList = ee.List([1,2,3,4,5,6,7,8,9,10,11,12,13,14])\n",
    "statisticTable = biomeList.map(biomeLevelStat).getInfo()\n",
    "# transform into data frame\n",
    "outputTable = pd.DataFrame(statisticTable,columns =['preAGB_Lower','preAGB_Upper','potAGB_Lower','potAGB_Upper','preRoot_Lower','preRoot_Upper','potRoot_Lower','potRoot_Upper','preLitter_Lower','preLitter_Upper','potLitter_Lower','potLitter_Upper']).round(1)\n",
    "outputTable.loc['sum'] = outputTable.sum() \n",
    "outputTable.to_csv('Data/BiomeLevelStatistics/StatisticsForModels/HM2_Uncertainty_for_diff_parts_at_Biome_Level.csv',header=True,mode='w+')\n",
    "print(colored('The biomass partition results in biome: \\n', 'blue', attrs=['bold']))\n",
    "outputTable.head(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If you got the error 'EEException: Too many concurrent aggregations.', please re-run this chunck of code again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
